<template>
  <a-card>
    <div class="card-header">
      <span class="card-header-title">数据字典</span>
      <a-button type="primary" @click="showModal"><plus-outlined/>新增</a-button>
    </div>
    <a-alert message="字典ID将作为唯一标识，请根据ID查询字典数据" banner class="margin-bottom"/>
    <a-table :columns="columns"
             :row-selection="{}"
             :data-source="data"
             :pagination="tablePageConfig">
      <template #bodyCell="{column,record}">
        <template v-if="column.dataIndex === 'status'">
          <a-tag v-if="record.status" color="blue">已启用</a-tag>
          <a-tag v-else color="error">已禁用</a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <div class="table-action">
            <span>编辑</span>
            <router-link :to="'/admin/dictionary/datasource?id='+record.id+'&name='+record.name">
              <span>数据管理</span>
            </router-link>
            <span @click="handleDelete(record.id)">删除</span>
          </div>
        </template>
      </template>
    </a-table>
  </a-card>
  <a-modal title="新增字典"
           v-model:open="state.open"
           :confirm-loading="state.loading"
           @ok="handleSubmit">
    <a-form :model="form" ref="formRef" :label-col="{span:4}" :wrapper-col="{span:19}" :rules="rules">
      <a-form-item label="字典名称" name="name">
        <a-input v-model:value="form.name"
                 placeholder="请输入10个字以内名称"
                 :maxlength="10"
                 show-count/>
      </a-form-item>
      <a-form-item label="状态">
        <a-radio-group button-style="solid" v-model:value="form.status">
          <a-radio-button :value="1">已启用</a-radio-button>
          <a-radio-button :value="0">已禁用</a-radio-button>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="备注" name="description">
        <a-textarea placeholder="请输入20字以内说明"
                    v-model:value="form.description"
                    show-count
                    :maxlength="20"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import {PlusOutlined} from "@ant-design/icons-vue";
import {tablePageConfig} from "@/config";
import {onMounted, reactive, ref} from "vue";
import {FormInstance} from "ant-design-vue";
import {getEnterpriseId, getUserId} from "@/plugin/auth";
import useMessage from "@/plugin/useMessage";
import {HttpResponse} from "@/api/request";
import {createDictionary, updateDictionary,getDictionaryList} from "@/api/modules/dictionary";
import {Modal} from 'ant-design-vue'
const formRef = ref<FormInstance>()

let data = ref<Dictionary[]>([])
let form = reactive<Dictionary>({
  id:0,
  name: '',
  description: '',
  status: 1,
  enterprise_id: getEnterpriseId(),
  user_id: getUserId()
})
const rules = {
  name: [{required: true, message: '请输入字典名称', trigger: 'blur'}]
}
const state = reactive({
  open: false,
  loading:false,
})
const showModal = (item?:DictionaryType) => {
  state.open = true
  if (!item.name){
    formRef.value?.resetFields()
  }else {
    form.id = item?.id
    form.name = item?.name
    form.description = item?.description
    form.status = item?.status
  }
}
const closeModal = () => {
  state.open = false
  formRef.value?.resetFields()
 }
const columns = [
  {title: 'ID', dataIndex: 'id', key: 'id',width: 80},
  {title: '名称', dataIndex: 'name', key: 'name',width: 200},
  {title: '描述', dataIndex: 'description', key: 'description'},
  {title: '状态', dataIndex: 'status', key: 'status',width:120},
  {title: '管理', key: 'action',width: 200},
]
const getDataList = async () => {
  const res = await getDictionaryList({
    user_id:form.user_id,
    enterprise_id:form.enterprise_id
  })
  if (res.code === 200){
    data.value = res.data
  }
}
const handleSubmit = async () => {
  let res:HttpResponse = {}
  formRef.value?.validate().then(async ()=>{
    state.loading = true
    if (!form.id) {
      delete form.id
      res = await createDictionary(form)
    } else {
      res = await updateDictionary(form.id,form)
    }
    if (res.code === 200){
      closeModal()
      await getDataList()
    }
    useMessage(res.code,res.message)
  }).catch(()=>{
    useMessage(403,'请输入正确的信息')
  }).finally(()=>{
    state.loading = false
  })
}
const handleDelete = (id:number) => {
  Modal.confirm({
    title: '删除字典',
    content: '确认删除该字典吗？',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      const res = await deleteDictionary(id)
      if (res.code === 200){
        await getDataList()
      }
      useMessage(res.code,res.message)
    }
  })
}
onMounted(()=>{
  getDataList()
})

</script>

<style scoped>

</style>